package engine.network.hostSide.mp;

import engine.network.hostSide.enums.RoleRequest;
import graphicUserInterface.elements.PositionListener;

import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class MultiPlayerHandling implements PositionListener{
	/* *********************************************************
	 * Attributes
	 * ********************************************************* */
	private HINBLocalPlayer _localPlayer;
	private HINBNetworkPlayer _networkPlayer;
	private List<HINBSpectator> _spectators;
	/* *********************************************************
	 * Constructor(s)
	 * ********************************************************* */
	public MultiPlayerHandling() {
		_localPlayer = new HINBLocalPlayer();
		_localPlayer.attach(this);
		_networkPlayer = null;
		_spectators = new LinkedList<HINBSpectator>();
	}
	
	public void handleNewConnexion(Socket s){
		//fst read if the new connection is a player request 
		//or a spectator one
		try {
			BufferedReader tempIn = 
				new BufferedReader(
						new InputStreamReader(s.getInputStream())
						);
			String req = tempIn.readLine();
			RoleRequest role = RoleRequest.factory(req);
			PrintWriter tempOut = 
				new PrintWriter(s.getOutputStream());
			switch (role) {
			case PLAYER:
				if(_networkPlayer == null){
					_networkPlayer = new HINBNetworkPlayer(s);
					_networkPlayer.attach(this);
					tempOut.println("OK");
					tempOut.flush();
					System.out.println("Multiplayer : newplayer registered");
				}else{
					tempOut.println("Error ");
					tempOut.flush();
					//TODO use an enum class right here and 
				}
				break;
			case SPECTATOR:
				HINBSpectator spect = new HINBSpectator(s);
				_spectators.add(spect);
				System.out.println("MultiPlayer : newSpect registered");
				break;
			default:
				System.out.println("MultiPlayer :  ouppps");
				//do nothing
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void update(Point p){
		Iterator<HINBSpectator> ite = _spectators.iterator();
		Point localPoint = _localPlayer.getPoint();
		Point networkPoint = _networkPlayer.getPoint();
		System.out.println("MultiPlayer : sending new positions ");
		System.out.println("\t"+localPoint+"\t"+networkPoint);
		while(ite.hasNext()){
			ite.next().setNewPoints(localPoint, networkPoint);
		}
	}
}
